<?php
if(!session_id()) { session_start(); }
if(!isset($_SESSION['user_id'])) {
	header('Location: index.php');
}
include_once('functions/main_functions.php');
	page_head();
?>
<h2>Stocks</h2>
<div id="content">
	<?php
		include_once('classes/stock.class.php');
		$stocks = new Stock();
		$list = $stocks->ViewAll();
		if($list == 0) {
			echo "There are no stocks listed.";
		} else {
			$popularity = 0;
			foreach($list as $item) {
				$popularity += $item['stock_count'];
			}
			echo '
			<table>
				<tr>
					<th>
						Stock Name
					</th>
					<th>
						Stock Price
					</th>
					<th>
						Stock Popularity
					</th>
			';
			if(isset($_SESSION['user_type'])) {
				echo '<th>Actions</th>';
			}
			echo '
				</tr>
			';
			foreach($list as $item) {
				if(isset($_SESSION['user_type'])) {
					echo '<tr class=' . $item['stock_id'] .'>';
						echo '<td>';
							echo '<input type="text" id="editable-stock-name" class="class' . $item['stock_id'] . '" value="' . $item['stock_name'] . '">';
						echo '</td>';
						echo '<td>';
							echo '<input type="text" id="editable-stock-price" class="class' . $item['stock_id'] . '" value="' . $item['stock_price'] . '">';
						echo '</td>';
						echo '<td>';
						if($popularity != 0) {
							echo round(($item['stock_count']/$popularity) * 100, 2) . "%";
						} else {
							echo "0%";
						}
						echo '</td>';
						echo '<td id="portfolio-actions"><a id="save-stock-changes" onclick="save_stock_changes(' . $item['stock_id'] . '); return false;">Save</a> | <a id="delete-stock" onclick="delete_stock('.$item['stock_id'] . '); return false;">Delete</a></td>';
					echo '</tr>';
				} else {
					echo '<tr>';
						echo '<td>';
							echo $item['stock_name'];
						echo '</td>';
						echo '<td>';
							echo $item['stock_price'];
						echo '</td>';
						echo '<td>';
						if($popularity != 0) {
							echo ($item['stock_count']/$popularity) * 100 . "%";
						} else {
							echo "0%";
						}
						echo '</td>';
					echo '</tr>';
				}
			}
		}
	?>
</div>
<?php
	page_foot();
?>